<?php
namespace app\admin\controller;
use app\model\Charge as ChargeModel;
use app\model\ChargeYp as ChargeYpModel;
use app\model\OrderBg as OrderBgModel;
use app\model\PaymentRecord as PaymentRecordModel;
use app\model\InvoiceRecord as InvoiceRecordModel;
use app\model\Order as OrderModel;
use app\model\Form as FormModel;
use app\model\Oform as OformModel;

use app\model\OformField as OformFieldModel;
use think\Db;


class Charge extends Base
{
    public function __construct(){
        $model = new ChargeModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
       
    }

    public function assignSearchs(){
        $model = $this->model;
        $search_params = [
            [
                ['key'=>'name','name'=>'项目名称','type'=>'text'],
                ['key'=>'type','name'=>'类型','type'=>'select1_1','params'=>$model->getTypeList()],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'type','type'=>'='],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $this->assignSearchs();

        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();

        $forms = Db::name('form')->select();
        $forms = arrayParamExtract($forms,'id','name');

        foreach ($list['data'] as $k => $vo) {
            $oforms = Db::name('oform')->where('order_id',$vo['id'])->select();
            $oform_content = [];
            foreach ($oforms as $oform_k => $oform_v) {
                // $form_name = $forms[$oform_v['form_id']];
                $form_name = FormModel::getTypeCn($oform_v['form_type']);
                $oforms[$oform_k]['form_name'] = $form_name;

                $oform_content[] = $form_name.' '.$oform_v['name'];
            }
            $list['data'][$k]['oforms'] = $oforms;
            $list['data'][$k]['oform_content'] = $oform_content;
            
            $list['data'][$k]['custom'] = Db::name('custom')->where('id',$vo['custom_id'])->find();
            $list['data'][$k]['order_price'] = Db::name('order_price')->where('order_id',$vo['id'])->find();

            $list['data'][$k]['yw_admin'] = Db::name('admin')->where('id',$vo['yw_aid'])->find();
            $list['data'][$k]['gj_admin'] = Db::name('admin')->where('id',$vo['gj_aid'])->find();
            $list['data'][$k]['admin'] = Db::name('admin')->where('id',$vo['c_aid'])->find();
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

 
    public function save(){
        $order_id = input('order_id');
        if (empty($order_id)) { $this->error('id不能为空'); }
        
        
        $ulogin = $this->login_user;
        $model = $this->model;
        if (request()->isPost()) {
            Db::startTrans();
            try{
                $fields = [
                    'must'=>['order_id','admin_id','payer_name','receivable_amount'],
                    'nomust'=>['standard','privilege_type','privilege_text','collection_account','collection_bank','collection_name','collection_remark','payment_account','payment_bank','payment_name','payment_ratepayer','payment_address','payment_tel','is_charge_monthly']
                ];
                $save_data = paramFilter(request()->param(),$fields);
                if (!empty($save_data['error_msg'])) {
                    throw new \Exception($save_data['error_msg']);
                }
                if ( $model->where('order_id',$order_id)->count() > 0 ) {
                    if ( $model->where('order_id',$order_id)->update($save_data) === false ) {
                        throw new \Exception('保存失败');
                    }
                }else{
                    $save_data['ctime'] = time();
                    if ( !$model->insert($save_data) ) {
                        throw new \Exception('保存失败');
                    }
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("保存成功",url('order/index'));
        }
        
        // $data = $model->where('order_id',$order_id)->find()->toarray();
        if (empty($data)) {
            $charge_id = $model->insert([
                'order_id'=>$order_id,
                'status'=>0
            ]);
            $data = [
                'id'=>$charge_id,
                'status'=>0,
                'admin_id'=>$ulogin['id']
            ];
        }

        $order = Db::name('order')->where('id',$order_id)->find();
        $order['yw_admin'] = Db::name('admin')->where('id',$order['yw_aid'])->find();
        $order['yw_admin']['department_name'] = Db::name('department')->where('id',$order['yw_admin']['department_id'])->value('name');
        $order['c_admin'] = Db::name('admin')->where('id',$order['c_aid'])->find();
        $order['c_admin']['company_name'] = Db::name('company')->where('id',$order['c_admin']['company_id'])->value('name');
        
        $order_price = Db::name('order_price')->field('id,order_id',true)->where('order_id',$data['id'])->find();
        $order_bg = Db::name('order_bg')->where('order_id',$order_id)->find();
        $order_bg['admin'] = Db::name('admin')->where('id',$order_bg['admin_id'])->find();

        $admins = Db::name('admin')->select();
        $admins = arrayParamExtract($admins,'id','truename');

        $payment_records = PaymentRecordModel::where('order_id',$order_id)->select();
        foreach ($payment_records as $k => $vo) {
            $payment_records[$k]['admin'] = Db::name('admin')->where('id',$vo['admin_id'])->find();
        }

        $invoice_records = InvoiceRecordModel::where('order_id',$order_id)->select();
        foreach ($invoice_records as $k => $vo) {
            $invoice_records[$k]['admin'] = Db::name('admin')->where('id',$vo['admin_id'])->find();
        }

        $statistics = [
            'receivable'=>$data['receivable_amount'],
            'yishou'=>PaymentRecordModel::where([
                ['order_id','=',$order_id],
                ['charge_type','=',0]
            ])->sum('amount'),
            'gongben'=>0,
            'yingtui'=>0,
            'yitui'=>0,
            'status'=>$model->getStatusCn($data['status'])
        ];

        $statistics['weishou'] = $statistics['receivable'] - $statistics['yishou'];

        $attach_types = Db::name('attach')->where([
            ['pid','=',0],
            ['group','=',3]
        ])->select();

        $attachs = Db::name('order_attach')->where([
            ['order_id','=',$order_id],
            ['group','=',3]
        ])->select();
        foreach ($attachs as $k => $vo) {
            $attachs[$k]['admin'] = Db::name('admin')->where('id',$vo['admin_id'])->find();
        }


        $this->assign([
            'admins'=>$admins,

            'attach_types'=>$attach_types,
            'OrderModel'=>new OrderModel(),
            'OrderBgModel'=>new OrderBgModel(),
            'PaymentRecordModel'=>new PaymentRecordModel(),
            'InvoiceRecordModel'=>new InvoiceRecordModel(),

            

            'data'=>$data,
            'payment_records'=>$payment_records,
            'invoice_records'=>$invoice_records,
            'order'=>$order,
            'order_bg'=>$order_bg,
            'statistics'=>$statistics,
            'attachs'=>$attachs
        ]);

        $this->assignFields();
        return view('save', [
            
        ]);
    }

    // 业务结单
    public function ywjd(){
        $model = $this->model;
        $fields = [
            'must'=>['order_id'],
            'nomust'=>['is_free','commission_ratio','commission_amount','commission_time','jd_time','jd_remark']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            throw new \Exception($save_data['error_msg']);
        }
        $save_data['status'] = 2;
        if ( $model->where('order_id',$save_data['order_id'])->update($save_data) !== false ) {
            return json(['code'=>2000,'msg'=>'更新成功']);
        }else{
            return json(['code'=>5000,'msg'=>'更新失败']);
        }
    }

    // 坏账登记
    public function hzdj(){
        $ulogin = $this->login_user;
        $model = $this->model;
        $fields = [
            'must'=>['order_id'],
            'nomust'=>['hz_amount','hz_remark']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            throw new \Exception($save_data['error_msg']);
        }
        $save_data['hz_aid'] = $ulogin['id'];
        if ( $model->where('order_id',$save_data['order_id'])->update($save_data) !== false ) {
            return json(['code'=>2000,'msg'=>'更新成功']);
        }else{
            return json(['code'=>5000,'msg'=>'更新失败']);
        }
    }

    // 附件
    public function uploadAttach(){
        $ulogin = $this->login_user;
        $fields = [
            'must'=>['order_id','name','savename'],
            'nomust'=>['type','extension']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            throw new \Exception($save_data['error_msg']);
        }
        $save_data['admin_id'] = $ulogin['id'];
        $save_data['ctime'] = time();
        $save_data['group'] = 3;
        if ( $id = Db::name('order_attach')->insertGetId($save_data) ) {
            $save_data['admin_name'] = $ulogin['truename'];
            $save_data['id'] = $id;
            $save_data['ctime'] = date('Y-m-d H:i',$save_data['ctime']);
            return json(['code'=>2000,'msg'=>'更新成功','data'=>$save_data]);
        }else{
            return json(['code'=>5000,'msg'=>'更新失败']);
        }
    }

    public function deleteAttach($attach_id){
        Db::name('order_attach')->where('id',$attach_id)->delete();
        return json(['code'=>2000,'msg'=>'更新成功']);
    }

}
